package com.example.smartrefreshdemo

import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.AdapterView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.smartrefreshdemo.adapter.BaseRecyclerAdapter
import com.example.smartrefreshdemo.adapter.SmartViewHolder
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import java.util.*
import kotlin.collections.ArrayList

class MainActivity : AppCompatActivity(), AdapterView.OnItemClickListener {

    private lateinit var adapter: BaseRecyclerAdapter<ItemData>
    val list = ArrayList<ItemData>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val recyclerView: RecyclerView = findViewById(R.id.recyclerView)

        for (i in 0..10) {
            list.add(ItemData(title = "title${i}", ds = "ds${i}"))
        }
        if (recyclerView is RecyclerView) {
            recyclerView.itemAnimator = DefaultItemAnimator()

            val manager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
            recyclerView.layoutManager = manager
            adapter = object :
                BaseRecyclerAdapter<ItemData>(
                    list, R.layout.item_layout, this
                ) {
                override fun onBindViewHolder(
                    holder: SmartViewHolder,
                    model: ItemData,
                    position: Int
                ) {
                    holder.text(R.id.title, model.title)
                    holder.text(R.id.ds, model.ds)
                    holder.textColorId(android.R.id.text2, R.color.black)
                }
            }

            recyclerView.adapter = adapter
        }

        val refreshLayout: SmartRefreshLayout = findViewById(R.id.refreshLayout)
        refreshLayout.setOnRefreshListener { it ->
            Log.d("SmartRefreshLayout", "SmartRefreshLayout")
            refreshLayout.finishRefresh(2000)
        }

        refreshLayout.setOnLoadMoreListener { it ->
            it.finishLoadMoreWithNoMoreData()
        }
    }

    override fun onItemClick(
        parent: AdapterView<*>?,
        recyclerView: View?,
        position: Int,
        id: Long
    ) {
        val oldData = ArrayList<ItemData>()
        list.forEach {
            oldData.add(it.copy())
        }

        list.add(8, ItemData("455", "da"))
        adapter.changeDataWithDiff(oldData, list)
    }
}